import { validateToken } from "./token";

/**
 * 设置登陆信息
 * @param {用户信息}  
 */
export const initLogin = (user, remember = false) => {
    if (remember) {
        // 持久化存储（关闭浏览器后仍然保留）
        localStorage.setItem('access_token', user.accessToken);
        localStorage.setItem('refresh_token', user.refreshToken);
        delete user.accessToken;
        delete user.refreshToken;
        localStorage.setItem('userId', user.userId);
        localStorage.setItem('tenantId', user.tenantId);
        localStorage.setItem('userinfo', JSON.stringify(user));
    } else {
        // 会话级存储（关闭浏览器后清除）
        sessionStorage.setItem('access_token', user.accessToken);
        sessionStorage.setItem('refresh_token', user.refreshToken);
        delete user.accessToken;
        delete user.refreshToken;
        sessionStorage.setItem('userId', user.userId);
        sessionStorage.setItem('tenantId', user.tenantId);
        sessionStorage.setItem('userinfo', JSON.stringify(user));
    }
}

export const getUserId = () => {
    return localStorage.getItem('userId') || sessionStorage.getItem('userId');
}

export const getTenantId = () => {
    return localStorage.getItem('tenantId') || sessionStorage.getItem('tenantId');
}

export const getUserInfo = () => {
    let userinfo = localStorage.getItem('userinfo') || sessionStorage.getItem('userinfo');
    if (userinfo) {
        return JSON.parse(userinfo);
    }
    return undefined
}

export const setAccessToken = (token) => {
    if (localStorage.getItem('access_token')) {
        localStorage.setItem('access_token', token);
    } else {
        sessionStorage.setItem('access_token', token);
    }
}

export const getAccessToken = () => {
    return localStorage.getItem('access_token') || sessionStorage.getItem('access_token');
};

export const getRefreshToken = () => {
    let token = localStorage.getItem('refresh_token') || sessionStorage.getItem('refresh_token');
    if (token && validateToken(token)) {
        return token;
    }
    return undefined;
}

export const clearLogin = () => {
    localStorage.removeItem('userinfo');
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('menus');
    localStorage.removeItem('userId');
    localStorage.removeItem('tenantId');

    sessionStorage.removeItem('userinfo');
    sessionStorage.removeItem('access_token');
    sessionStorage.removeItem('refresh_token');
    sessionStorage.removeItem('userId');
    sessionStorage.removeItem('tenantId');
}

export const getMenus = () => {
    let menus = localStorage.getItem('menus');
    return menus ? JSON.parse(menus) : [];
}